package com.bosssoft.trainee.nontax.common.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuqiang
 * @date 2022/6/21 16:04
 * 统一异常处理
 */

@RestControllerAdvice
public class MyControllerAdvice {

    /**
     * 全局异常捕捉处理
     *
     * @param ex Exception
     * @return Map
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, String> errorHandler(Exception ex) {
        Map<String, String> map = new HashMap<>();
        map.put("code", "100");
        map.put("msg", ex.getMessage());
        return map;
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     *
     * @param ex MyException
     * @return Map
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Map<String, String> myErrorHandler(MyException ex) {
        Map<String, String> map = new HashMap<>();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }

}
